#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);

    assert(n != -1);
    (void)n;

    pid_t id = fork();
    assert(id != -1);

    if (id == 0) // 子进程一直写
    {
        close(pipefd[0]);
        string msg = "I am child";
        char send_buffer[128];
        while (true)
        {
            snprintf(send_buffer, sizeof(send_buffer), "%s[%d]", msg.c_str(), getpid());
            write(pipefd[1], send_buffer, strlen(send_buffer));
            sleep(1);
        }
    }

    close(pipefd[1]);
    char receive_buffer[128];
    int count = 5;
    while (count--)
    {
        ssize_t s = read(pipefd[0], receive_buffer, sizeof(receive_buffer) - 1);
        if (s > 0)
        {
            receive_buffer[s] = 0; // 字符串自定义约定
            cout << "father[" << getpid() << "] get a msg: " << receive_buffer << endl;
        }
    }
    close(pipefd[0]); // 关闭读端

    int status = 0;
    waitpid(id, &status, 0);
    if (WIFEXITED(status))
    {
        printf("child_pid: %d exit_code: %d\n", id, WEXITSTATUS(status));
    }
    else
    {
        printf("child_pid: %d exit_signal: %d core_dump: %d\n", id, status & (0x7f), (status >> 7) & 1);
    }

    return 0;
}
